package com.atyjh.reggie.controller;

import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.entity.Dish;
import com.atyjh.reggie.entity.ShoppingCart;
import com.atyjh.reggie.service.IShoppingCartService;
import com.atyjh.reggie.utils.UserHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.22
 */
@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

    @Resource
    private IShoppingCartService shoppingCartService;

    @RequestMapping("/list")
    public Result<List<ShoppingCart>> list() {

        LambdaQueryWrapper<ShoppingCart> slqw = new LambdaQueryWrapper<>();
        slqw.eq(ShoppingCart::getUserId, UserHolder.getUser().getId());
        List<ShoppingCart> list = shoppingCartService.list(slqw);
        return Result.success(list);

    }

    @PostMapping("/add")
    public Result<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
//        给商品设置用户id
        shoppingCart.setUserId(UserHolder.getUser().getId());
//        查询购物车中是否已经有了这个商品
        LambdaQueryWrapper<ShoppingCart> sclqw = new LambdaQueryWrapper<>();
        sclqw.eq(ShoppingCart::getUserId, UserHolder.getUser().getId());
        if (shoppingCart.getDishId() != null) {
            sclqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            sclqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart item = shoppingCartService.getOne(sclqw);

        if (item == null) {
//            如果没有这个商品，就添加到购物车中
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            item = shoppingCart;
        } else {
//            如果购物车中有了，就把数量+1
            Integer number = item.getNumber();
            item.setNumber(++number);
            shoppingCartService.updateById(item);
        }
        return Result.success(item);
    }

}
